﻿using Microsoft.Win32;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;

using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace OverSizeImageDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : System.Windows.Window
    {
        bool bitTaskRun = false;

        public MainWindow()
        {
            Environment.SetEnvironmentVariable("OPENCV_IO_MAX_IMAGE_PIXELS", "10000000000");
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button button = (Button)sender;
            if (button == null) return;
            switch (button.Tag.ToString())
            {
                case "导入普通图片":
                    InputNormalImage();
                    break;
                case "导入大图":
                    InputBigImage();
                    break;
                case "导入位图":
                    InputBitImage();
                    break;
                case "停止":
                    bitTaskRun = false;
                    break;
            }

        }

        private void InputNormalImage()
        {
            OpenFileDialog dialog = new OpenFileDialog();
            if (dialog.ShowDialog() == true)
            {
                image.LoadModel = OverSizeImage.ImageLoadModelEnum.正常;
                image.Status = OverSizeImage.ImageStatusEnum.浏览;
                image.MoveOverEnabled = true;
                image.DecodePixelEnabled = false;
                image.DecodePixelValue = 1080;
                if (int.TryParse(txt_Decode.Text, out int decode))
                {
                    if (decode > 0)
                    {
                        image.DecodePixelEnabled = true;
                        image.DecodePixelValue = decode;
                    }
                }
                image.ImagePath = dialog.FileName;
            }
        }

        private void InputBitImage()
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                image.LoadModel = OverSizeImage.ImageLoadModelEnum.位图;
                image.Status = OverSizeImage.ImageStatusEnum.浏览;
                image.MoveOverEnabled = false;
                if ((bool)cbx_dir.IsChecked)
                {
                    if (int.TryParse(txt_Dir_X.Text, out int dX))
                        image.Dirty_X = dX;
                    else
                    {
                        MessageBox.Show("请输入正确的脏区X");
                        return;
                    }
                    if (int.TryParse(txt_Dir_Y.Text, out int dY))
                        image.Dirty_Y = dY;
                    else
                    {
                        MessageBox.Show("请输入正确的脏区Y");
                        return;
                    }
                    if (int.TryParse(txt_Dir_W.Text, out int dW))
                        image.Dirty_Width = dW;
                    else
                    {
                        MessageBox.Show("请输入正确的脏区Width");
                        return;
                    }
                    if (int.TryParse(txt_Dir_H.Text, out int dH))
                        image.Dirty_Height = dH;
                    else
                    {
                        MessageBox.Show("请输入正确的脏区Height");
                        return;
                    }
                }
                else
                {
                    image.Dirty_X = -1;
                    image.Dirty_Y = -1;
                    image.Dirty_Width = -1;
                    image.Dirty_Height = -1;
                }
                if ((bool)cbx_STA.IsChecked)
                    image.IsSTA = true;
                else
                    image.IsSTA = false;
                if (int.TryParse(txt_Frame.Text, out int frame))
                {
                    if (frame > 0)
                    {
                        Task.Run(() => BitImageTask(dialog.SelectedPath, frame));
                    }
                    else
                        MessageBox.Show("请输入正确的帧率");
                }
                else
                {
                    MessageBox.Show("请输入正确的帧率");
                }
            }
        }

        private void BitImageTask(string selectedPath, int frame)
        {
            List<Mat> matList = new List<Mat>();
            foreach (var item in Directory.GetFiles(selectedPath, "*.jpg"))
            {
                matList.Add(new Mat(item, ImreadModes.Unchanged));
            }
            if (matList.Count > 0)
            {
                bitTaskRun = true;
                int interval = 1000 / frame;
                int index = 0;
                while (bitTaskRun)
                {
                    Stopwatch sw = Stopwatch.StartNew();
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        image.GetMat(matList[index % matList.Count].Clone());
                    }));
                    index++;
                    sw.Stop();
                    int waitMs = interval - sw.ElapsedMilliseconds > 0 ? interval - (int)sw.ElapsedMilliseconds : 0;
                    Thread.Sleep(waitMs);   
                }
            }
            bitTaskRun = false;
        }

        private void InputBigImage()
        {
            OpenFileDialog dialog = new OpenFileDialog();
            if (dialog.ShowDialog() == true)
            {
                image.LoadModel = OverSizeImage.ImageLoadModelEnum.瓦片;
                image.Status = OverSizeImage.ImageStatusEnum.浏览;
                image.MoveOverEnabled = false;
                image.ImagePath = dialog.FileName;
            }
        }

        private void Cbx_Editor_Checked(object sender, RoutedEventArgs e)
        {
            image.Status = OverSizeImage.ImageStatusEnum.编辑;
        }

        private void Cbx_Editor_Unchecked(object sender, RoutedEventArgs e)
        {
            image.Status = OverSizeImage.ImageStatusEnum.浏览;
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox temp = sender as ComboBox;
            if (temp == null) return;
            image.SelectedShape = (OverSizeImage.ShapeEnum)temp.SelectedIndex;
        }

        private void Cbx_ManualScale_Checked(object sender, RoutedEventArgs e)
        {
            image.MouseWheelEnabled = false;
        }

        private void Cbx_ManualScale_Unchecked(object sender, RoutedEventArgs e)
        {
            image.MouseWheelEnabled = true;
        }
    }
}
